package com.hx.base.servlet.excel;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.dispatcher.StrutsResultSupport;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;

@SuppressWarnings("serial")
public class ExcelResult extends StrutsResultSupport {
	private String dataList = "dataList";
	private String fileName = "fileName";

	@SuppressWarnings("unchecked")
	@Override
	protected void doExecute(String finalLocation, ActionInvocation invocation)
			throws Exception {
		ActionContext ctx = invocation.getInvocationContext();
		HttpServletRequest request = (HttpServletRequest) ctx
				.get(org.apache.struts2.StrutsStatics.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ctx
				.get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE);
		String excelfile = (String) request.getAttribute(fileName);
		setXlsHeader(response, excelfile);
		OutputStream os = response.getOutputStream();
		List list = (List) request.getAttribute(dataList);
		ExcelExport.export(list, os);
		os.close();
	}

	public void setDataList(String dataList) {
		this.dataList = dataList;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	private void setXlsHeader(HttpServletResponse rs, String fn)
			throws UnsupportedEncodingException {
		rs.setContentType("application/vnd.ms-excel");
		String fileName = new String(fn.getBytes("GBK"), "ISO-8859-1");
		rs.setHeader("Content-disposition", "attachment; filename=" + fileName);
	}
}
